import { ref, unref } from 'vue';

type OnlyOneChildType = AppRouteRecordRaw & { noShowingChildren?: boolean };
interface HasOneShowingChild {
  oneShowingChild?: boolean;
  onlyOneChild?: OnlyOneChildType;
}

export const hasOneShowingChild = (children: AppRouteRecordRaw[] = [], parent: AppRouteRecordRaw): HasOneShowingChild => {
  const onlyOneChild = ref<OnlyOneChildType>();

  const showingChildren = children.filter((v) => {
    const meta = v?.meta ?? {};
    if (meta?.hidden) {
      return false;
    } else {
      onlyOneChild.value = v;
      return true;
    }
  });

  if (showingChildren.length === 1) {
    return {
      oneShowingChild: true,
      onlyOneChild: unref(onlyOneChild)
    };
  }

  if (!showingChildren.length) {
    onlyOneChild.value = { ...parent, path: '', noShowingChildren: true };

    return {
      oneShowingChild: false,
      onlyOneChild: unref(onlyOneChild)
    };
  }

  return {
    oneShowingChild: false,
    onlyOneChild: unref(onlyOneChild)
  };
};
